package com.net;

import java.io.InputStream;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by cjx on 2019/10/22
 * 说明：提供一个网络工具
 */
public class RetrofitUtils {

    private static volatile RetrofitUtils utils;

    private EasyLogInterceptor interceptor;
    private HashMap<String, Retrofit> retrofits;

    private OkHttpClient defaultClient;

    public static RetrofitUtils getInstance() {
        if (utils == null) {
            synchronized (RetrofitUtils.class) {
                if (utils == null) {
                    utils = new RetrofitUtils();
                }
            }
        }
        return utils;
    }

    private RetrofitUtils() {
        interceptor = new EasyLogInterceptor();
        retrofits = new HashMap<>(1);
    }

    public void setLogCallback(LogCallback logCallback) {
        if (interceptor != null) {
            interceptor.setLogCallback(logCallback);
        }
    }

    public <T> T create(String url, final Class<T> service) {
        return create(url, service, null);
    }

    public <T> T create(String url, final Class<T> service, InputStream inputStream) {
        Retrofit retrofit = retrofits.get(url);
        if (retrofit == null) {
            OkHttpClient c;
            if (inputStream == null) {
                if (defaultClient == null) {
                    defaultClient = getClient(null);
                }
                c = defaultClient;
            } else {
                c = getClient(inputStream);
            }
            retrofit = new Retrofit.Builder()
                    .baseUrl(url)
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(c)
                    .build();
            retrofits.put(url, retrofit);
        }
        return retrofit.create(service);
    }

    // 获取带证书的client
    public OkHttpClient getClient(InputStream inputStream) {
        OkHttpClient.Builder builder = setSSL(new OkHttpClient.Builder(), inputStream);

        // 简单打印发送的地址和接收到的数据
        builder.addInterceptor(interceptor);

        OkHttpClient client = builder.connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .build();
        return client;
    }
    /**
     * 添加证书
     */
    public OkHttpClient.Builder setSSL(OkHttpClient.Builder builder, final InputStream inputStream) {
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            MyX509TrustManager x509TrustManager = new MyX509TrustManager(inputStream);
            TrustManager[] trustManagers = {x509TrustManager};
            sslContext.init(null, trustManagers, new java.security.SecureRandom());
            final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            builder.sslSocketFactory(sslSocketFactory, x509TrustManager);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            return builder;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return builder;
    }

}
